import express, { Express, NextFunction } from 'express'
import cors from 'cors'
import 'reflect-metadata'
import CommonResponse from '../utils/commonRes.ts'

const bodyParser = require('body-parser')

export interface CustomResponse extends Response {
  commonRes: CommonResponse // 添加自定义属性
}
const injectCommonResponse = (req: Request, res: CustomResponse, next: NextFunction) => {
  // @ts-ignore
  res.commonRes = new CommonResponse(res)
  // console.log(1, res.commonRes)
  next()
}

function initMiddleware(app: Express) {
  require('express-async-errors')
  app.use(express.json())
  // 跨域设置
  app.use(cors())

  // 统一返回格式
  app.use(injectCommonResponse)

  // 解析请求体中的 JSON 数据
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({ extended: true }))

  // 设置静态文件目录
  app.use(express.json())
  // app.use(express.static('../client'))
}

export default initMiddleware
